package com.liuzh.kaoyanspringboot.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liuzh.kaoyanspringboot.common.Result;
import com.liuzh.kaoyanspringboot.config.AuthAccess;
import com.liuzh.kaoyanspringboot.entity.Comment;
import com.liuzh.kaoyanspringboot.service.CommentService;
import com.liuzh.kaoyanspringboot.service.MessageService;
import com.liuzh.kaoyanspringboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器 评论
 * </p>
 *
 * @author 刘志鸿
 * @since 2023-03-11
 */
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private MessageService messageService;

    // 新增或更新
    @PostMapping
    public Result save(@RequestBody Comment comment) {
        if (comment.getId() == null) {
            comment.setUserId(TokenUtils.getCurrentUser().getId());
            comment.setTime(DateUtil.now());
            commentService.save(comment);
            if (comment.getPid() != null) {  // 当该评论是回复时，对被回复用户进行通告
                messageService.createComment(comment);
            }
        }
        // 理论上是没有修改评论的
        commentService.updateById(comment);
        return Result.success(true);
    }

    // 根据 id 删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(commentService.removeById(id));
    }

    // 批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(commentService.removeBatchByIds(ids));
    }

    //查询所有数据
    @GetMapping
    public Result findAll() {
        return Result.success(commentService.list());
    }

    //查询所有数据
    @AuthAccess
    @GetMapping("tree/{articleId}")
    public Result findTree(@PathVariable Integer articleId) {
        List<Comment> articleComments = commentService.findCommentDetail(articleId);
        return Result.success(articleComments);
    }

    // 根据 id 查询
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(commentService.getById(id));
    }

    //简单的分页查询
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return Result.success(commentService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

}

